<template>
  <div class="MenuManage">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>门户管理</el-breadcrumb-item>
      <el-breadcrumb-item><a>菜单管理</a></el-breadcrumb-item>
    </el-breadcrumb>
    <el-tabs v-model="activeName">
      <el-tab-pane label="导航菜单" name="navigation">
        <div class="navigation-content">
          <div class="navigation-top">
            <el-button
              type="primary"
              icon="el-icon-circle-plus-outline"
              @click="operate('add')"
              >新建</el-button
            >
            <el-input
              placeholder="请输入菜单名称"
              suffix-icon="el-icon-search"
              @keydown.native.enter="search"
              v-model="searchInfo"
            ></el-input>
          </div>
          <el-table :data="navigationData" class="scroll-content">
            <el-table-column
              label="菜单名称"
              width="100"
              prop="menu_name.zh"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              label="访问路径"
              width="390"
              prop="visit_url"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column label="是否开启" prop="status">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.status"
                  @change="switchChange(scope.row)"
                >
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column label="顺序" prop="order"></el-table-column>
            <el-table-column label="创建人">
              <template slot-scope="scope">
                <show-person :person-info="scope.row.creator"></show-person>
              </template>
            </el-table-column>
            <el-table-column
              label="创建时间"
              prop="create_time"
              show-overflow-tooltip
              width="160"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-tooltip effect="dark" content="编辑" placement="top">
                  <i
                    class="el-icon-edit"
                    @click="operate('edit', scope.row)"
                  ></i>
                </el-tooltip>
                <i
                  class="el-icon-delete disable"
                  v-if="scope.row.is_locked"
                ></i>
                <el-tooltip v-else effect="dark" content="删除" placement="top">
                  <i
                    class="el-icon-delete"
                    @click="operate('delete', scope.row)"
                  ></i>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="paginationInfo.current_page"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="paginationInfo.page_size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="paginationInfo.total"
            background
          >
          </el-pagination>
        </div>
      </el-tab-pane>
      <el-tab-pane label="信息模块" name="information">
        <div class="information-content">
          <el-table :data="informationData">
            <el-table-column
              label="信息模块名称"
              prop="menu_name.zh"
            ></el-table-column>
            <el-table-column label="icon" prop="icon_url">
              <template slot-scope="scope">
                <i :class="scope.row.icon_url"></i>
              </template>
            </el-table-column>
            <el-table-column label="显示icon" prop="show_icon">
              <template slot-scope="scope">
                <el-switch
                  v-if="scope.row.icon_url"
                  v-model="scope.row.show_icon"
                  @change="showIconChange(scope.row)"
                ></el-switch>
              </template>
            </el-table-column>
            <el-table-column label="修改人" prop="updater">
              <template slot-scope="scope">
                <show-person :person-info="scope.row.updater" />
              </template>
            </el-table-column>
            <el-table-column label="修改时间" prop="update_time">
              <template slot-scope="scope">
                {{ getFormatDate(scope.row.update_time) }}
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click="edit(scope.row)">编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>
    <el-dialog
      :title="`${todo}菜单`"
      :visible.sync="dialogVisible"
      width="30%"
      custom-class="menu-manage-dialog"
      :before-close="beforeClose"
    >
      <el-form
        :model="navigationForm"
        label-position="top"
        :rules="rules"
        ref="elForm"
      >
        <el-form-item label="菜单名称" prop="menu_name">
          <el-input
            v-model="navigationForm.menu_name.zh"
            placeholder="菜单名称"
            maxlength="8"
          ></el-input>
          <el-popover
            placement="bottom-end"
            popper-class="navigationForm-popper"
            v-model="navigationFormPopperShow"
          >
            <el-form :data="navigationForm" :rules="rules" label-width="60px">
              <el-form-item label="中文：">
                <el-input
                  v-model="navigationForm.menu_name.zh"
                  placeholder="请输入"
                  maxlength="8"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item label="英文：">
                <el-input
                  v-model="navigationForm.menu_name.en"
                  placeholder="please input"
                  maxlength="30"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button
                  size="small"
                  @click="navigationFormPopperShow = false"
                  >取消</el-button
                >
                <el-button
                  type="primary"
                  size="small"
                  @click="navigationFormPopperShow = false"
                  >确定</el-button
                >
              </el-form-item>
            </el-form>
            <i slot="reference" class="iconfont icon-guojihua"></i>
          </el-popover>
        </el-form-item>
        <el-form-item label="访问路径" prop="visit_url">
          <el-input
            v-model="navigationForm.visit_url"
            placeholder="链接路径"
            :disabled="navigationForm.is_locked ? true : false"
          ></el-input>
        </el-form-item>
        <el-form-item label="顺序" prop="order">
          <el-input v-model="navigationForm.order"></el-input>
        </el-form-item>
        <el-form-item label="是否开启" prop="status" class="inline">
          <el-switch v-model="navigationForm.status"></el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit('navigation')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      title="编辑信息模块"
      :visible.sync="editInfoVisible"
      width="40%"
      custom-class="menu-manage-module-dialog"
    >
      <el-form :model="informationForm" :rules="rule" ref="editInfoForm">
        <el-form-item label="信息模块名称" prop="infoModuleName">
          <el-input
            v-model="informationForm.infoModuleName.zh"
            placeholder="请输入名称"
          ></el-input>
          <el-popover
            placement="bottom-end"
            popper-class="informationForm-popper"
            v-model="informationFormPopperShow"
          >
            <el-form :data="informationForm" :rules="rule" label-width="60px">
              <el-form-item label="中文：">
                <el-input
                  v-model="informationForm.infoModuleName.zh"
                  placeholder="请输入"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item label="英文：">
                <el-input
                  v-model="informationForm.infoModuleName.en"
                  placeholder="please input"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button
                  size="small"
                  @click="informationFormPopperShow = false"
                  >取消</el-button
                >
                <el-button
                  type="primary"
                  size="small"
                  @click="informationFormPopperShow = false"
                  >确定</el-button
                >
              </el-form-item>
            </el-form>
            <i slot="reference" class="iconfont icon-guojihua"></i>
          </el-popover>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editInfoVisible = false" size="small"
          >取 消</el-button
        >
        <el-button type="primary" @click="submit('editInfo')" size="small"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import showPerson from "@/components/public/showPerson.vue";
import {
  addNavMenu,
  changeStatus,
  deleteNavMenu,
  editNavMenu,
  getAllInfoBlock,
  getAllNavMenu,
  searchNavMenu,
  updateInfoBlock,
} from "@/http/api";
import dayjs from "dayjs";
export default {
  name: "MenuManage",
  components: { showPerson },
  data() {
    return {
      activeName: "navigation",
      navigationData: [],
      informationData: [],
      searchInfo: "",
      todo: "",
      dialogVisible: false,
      navigationForm: {
        menu_name: {
          zh: "",
          en: "",
        },
        visit_url: "",
        order: 1,
        status: false,
        is_locked: 0,
      },
      editInfoVisible: false,
      informationForm: {
        infoModuleName: {
          zh: "",
          en: "",
        },
      },
      rules: {
        menu_name: [
          {
            required: true,
            validator: (_, value, callback) => {
              if (!value.zh.length) {
                callback(new Error("请输入菜单名称"));
              } else {
                callback();
              }
            },
          },
        ],
        visit_url: [
          {
            required: true,
            validator: (_, value, callback) => {
              if (!value) {
                callback(new Error("请输入链接地址"));
              } else {
                let res =
                  /^(((ht|f)tps?):\/\/)?[\w-]+(.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?$/.test(
                    value
                  );
                res ? callback() : callback(new Error("请输入正确链接地址"));
              }
            },
          },
        ],
        order: [
          {
            required: true,
            validator: (_, value, callback) => {
              if (!value) {
                callback();
              }
              if (
                isNaN(Number(value)) ||
                Number(value) < 0 ||
                Math.floor(Number(value)) !== Number(value)
              ) {
                callback(new Error("只能输入大于0的整数"));
              }
              callback();
            },
          },
        ],
      },
      rule: {
        infoModuleName: [
          {
            required: true,
            validator: (_, value, callback) => {
              if (!value.zh.length || value.zh.length > 8) {
                callback(new Error("请输入模块名称,最多可输入8个字"));
              } else {
                callback();
              }
            },
          },
        ],
      },
      paginationInfo: {
        current_page: 1,
        total: 0,
        page_size: 10,
      },
      informationFormPopperShow: false,
      navigationFormPopperShow: false,
      editRow: {},
    };
  },
  mounted() {
    this.getNavMenu();
    this.getAllInfoBlocks();
  },
  methods: {
    async search() {
      this.paginationInfo = {
        current_page: 1,
        total: 0,
        page_size: 10,
      };
      let res = await searchNavMenu({
        ...this.paginationInfo,
        key: this.searchInfo,
      });
      if (res.code === 20041) {
        this.paginationInfo = res.data.page;
        this.navigationData = res.data.rows;
        this.navigationData.forEach((item) => {
          item.status = item.status === 1 ? true : false;
          item.create_time = dayjs(item.create_time).format(
            "YYYY-MM-DD HH:mm:ss"
          );
        });
      }
    },
    operate(mode, currentRow) {
      if (mode !== "delete") {
        this.todo = mode === "add" ? "新建" : "编辑";
        if (mode === "edit") {
          for (const key in this.navigationForm) {
            this.navigationForm[key] = currentRow[key];
          }
          this.navigationForm.menu_id = currentRow.menu_id;
        }
        this.dialogVisible = true;
        this.$refs.elForm.clearValidate();
      } else {
        this.$alert(`是否确认删除？`, "删除", {
          confirmButtonText: "确定",
          showCancelButton: true,
          type: "warning",
          callback: async (action) => {
            if (action === "confirm") {
              let res = await deleteNavMenu(currentRow.menu_id);
              if (res.code === 20021) {
                this.$message({
                  message: "删除成功",
                  type: "success",
                });
                this.getNavMenu();
              } else {
                this.$message.error(res.msg);
              }
            }
          },
        });
      }
    },
    submit(mode) {
      if (mode !== "editInfo") {
        this.$refs.elForm.validate(async (res) => {
          if (res) {
            let data = { ...this.navigationForm };
            data.status = data.status ? 1 : 0;
            data.order = parseInt(data.order);
            let res = {};
            if (data.menu_id !== undefined) {
              res = await editNavMenu(data);
            } else {
              res = await addNavMenu(data);
            }
            if (res.code === 20011 || res.code === 20031) {
              this.$message.success(
                res.code === 20031 ? "编辑成功" : "添加成功"
              );
              this.dialogVisible = false;
              this.getNavMenu();
            } else {
              this.$message.success(res.msg);
            }
          }
        });
      } else {
        this.$refs.editInfoForm.validate(async (res) => {
          if (res) {
            let res_info = await updateInfoBlock(
              Object.assign(this.editRow, {
                menu_name_zh: this.informationForm.infoModuleName.zh,
                menu_name_en: this.informationForm.infoModuleName.en,
                show_icon: this.editRow.show_icon ? 1 : 0,
              })
            );
            if (res_info.code === 20031) {
              this.editInfoVisible = false;
              this.getAllInfoBlocks();
            }
          }
        });
      }
    },
    beforeClose() {
      this.dialogVisible = false;
      setTimeout(() => {
        this.navigationForm = {
          menu_name: {
            zh: "",
            en: "",
          },
          visit_url: "",
          order: 1,
          status: false,
        };
      }, 200);
    },
    handleSizeChange() {
      console.log("handleSizeChange");
    },
    handleCurrentChange() {
      console.log("handleCurrentChange");
    },
    edit(row) {
      this.informationForm.infoModuleName.zh = row.menu_name.zh;
      this.informationForm.infoModuleName.en = row.menu_name.en;
      this.editRow = row;
      this.editInfoVisible = true;
    },
    getFormatDate(timestamp) {
      return dayjs(timestamp).format("YYYY-MM-DD HH:mm:ss");
    },
    async showIconChange(row) {
      let data = Object.assign(row, {
        updater_id: JSON.parse(localStorage.getItem("userInfo") || "")
          .employee_id,
        show_icon: row.show_icon ? 1 : 0,
      });
      let res = await updateInfoBlock(data);
      if (res.code == 20031) {
        row.show_icon = row.show_icon ? true : false;
      }
    },
    async getAllInfoBlocks() {
      let res = await getAllInfoBlock();
      if (res.code === 20041) {
        this.informationData = res.data;
        this.informationData.forEach((element) => {
          element.show_icon = element.show_icon ? true : false;
        });
      }
    },
    async getNavMenu() {
      let res = await getAllNavMenu({ ...this.paginationInfo });
      if (res.code === 20041) {
        this.paginationInfo = res.data.page;
        this.navigationData = res.data.rows;
        this.navigationData.forEach((item) => {
          item.status = item.status === 1 ? true : false;
          item.create_time = dayjs(item.create_time).format(
            "YYYY-MM-DD HH:mm:ss"
          );
        });
      }
    },
    async switchChange(row) {
      let res = await changeStatus({
        menu_id: row.menu_id,
        status: row.status ? 1 : 0,
      });
      if (res.code === 20031) {
        this.$message.success(row.status ? "开启成功" : "关闭成功");
      } else {
        this.$message.error(res.msg);
      }
    },
  },
};
</script>
<style lang="less" scoped>
.MenuManage {
  .navigation-content {
    padding: 20px;
    background-color: #fff;
    border-radius: 6px;
    height: calc(100vh - 200px);
    .navigation-top {
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
      .el-input {
        width: 320px;
      }
    }
    /deep/ .el-table {
      height: calc(100vh - 320px);
      margin-bottom: 10px;
      .el-icon-edit,
      .el-icon-delete {
        cursor: pointer;
        margin-right: 8px;
        &.disable {
          color: #c0c4cc;
        }
      }
    }
    .el-pagination {
      display: flex;
      justify-content: end;
    }
  }
  .information-content {
    padding: 20px;
    background-color: #fff;
    border-radius: 6px;
    height: calc(100vh - 200px);
    i {
      color: #5682ff;
      font-size: 20px;
    }
  }
}
</style>
<style lang="less">
.menu-manage-dialog {
  .el-dialog__body {
    padding: 10px 20px;
    border-top: 1px solid #e9e9e9;
    border-bottom: 1px solid #e9e9e9;
    .el-form-item__label {
      padding: 0;
    }
    .inline {
      display: flex;
      label {
        margin-right: 10px;
      }
    }
    .icon-guojihua {
      position: absolute;
      right: 10px;
    }
  }
}
.menu-manage-module-dialog {
  border-radius: 6px;
  overflow: hidden;
  .el-dialog__header {
    padding: 20px;
    background-color: #4c78fc;
    .el-dialog__title,
    .el-dialog__close {
      color: #fff;
    }
  }
  .icon-guojihua {
    position: absolute;
    right: 10px;
  }
  .el-button--primary {
    background: #4c78fc;
  }
}
.informationForm-popper,
.navigationForm-popper {
  .el-button--primary {
    background: #4c78fc;
  }
  .el-form .el-form-item:last-child {
    margin-bottom: 0;
  }
}
</style>
